package main

import (
	"github.com/axgle/mahonia"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

// PathExists 判断文件夹是否存在
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

// Mkdir 创建文件夹
func Mkdir(path string) (bool, error) {
	_path, err := filepath.Abs(path)
	if err == nil {
		path = _path
	}
	exist, _ := PathExists(path)
	if !exist {
		err := os.Mkdir(path, os.ModePerm)
		if err != nil {
			return false, err
		}
	}
	return true, nil
}

// ListDir 遍历当前目录
func ListDir(dirPth string, suffix string) ([]string, error) {
	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
		return nil, err
	}
	var files []string
	PthSep := string(os.PathSeparator)
	suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写

	for _, fi := range dir {
		if fi.IsDir() { // 忽略目录
			continue
		}
		if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) { //匹配文件
			files = append(files, dirPth+PthSep+fi.Name())
		}
	}
	return files, nil
}

// SaveFile 保存文件
func SaveFile(path string, reader io.Reader) error {
	var (
		readN    int
		file     *os.File
		readErr  error
		writeErr error
	)
	file, readErr = os.Create(path)
	if readErr != nil {
		return readErr
	}
	buf := make([]byte, 2048)
	for {
		if readN, readErr = reader.Read(buf); readN > 0 {
			_, writeErr = file.Write(buf[0:readN])
			if writeErr != nil {
				return writeErr
			}
			if readErr == io.EOF {
				return nil
			}
		} else {
			return readErr
		}
	}
}

// Convert 编码转换
func Convert(buf []byte, srcCode string, tagCode string) []byte {
	srcCoder := mahonia.NewDecoder(srcCode)
	srcResult := srcCoder.ConvertString(string(buf))
	tagCoder := mahonia.NewDecoder(tagCode)
	_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)
	return cdata
}

// ConvertGBK2utf8  GBK==>UTF-8
func ConvertGBK2utf8(buf []byte) []byte {
	return Convert(buf, "gbk", "utf8")
}

// ConvertToString 编码转换
func ConvertToString(buf string, srcCode string, tagCode string) string {
	srcCoder := mahonia.NewDecoder(srcCode)
	srcResult := srcCoder.ConvertString(buf)
	tagCoder := mahonia.NewDecoder(tagCode)
	_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)
	return string(cdata)
}

// ConvertGBK2utf8String  GBK==>UTF-8
func ConvertGBK2utf8String(buf string) string {
	return ConvertToString(strings.Trim(buf, " "), "gbk", "utf8")
}
